/*
 * @Description:角色
 * @Author: Haor
 * @Date: 2022-05-11 11:34:14
 * @LastEditTime: 2022-05-11 14:09:57
 * @LastEditors: Haor
 */
import { Injectable } from '@nestjs/common'
import { InjectRepository } from '@nestjs/typeorm'
import { Role } from '@entities/role.entity'
import { Repository } from 'typeorm'
import { HttpResult } from '@libs/http.result'
import { CreateRoleDto } from '@dto/create-role.dto'
import { format } from '@utils/date'
import { BusinessException } from '@exceptions'

@Injectable()
export class RoleService {
	constructor(
		@InjectRepository(Role)
		private readonly roleRepository: Repository<Role>
	) {}

	/**
	 * 查询角色列表
	 */
	public async getRoleList() {
		const data = await this.roleRepository.find()
		return HttpResult.success(data)
	}

	/**
	 * 通过名称获取角色
	 * @param name 角色名称
	 * @private
	 */
	private getRoleByName(name: string) {
		return this.roleRepository.findOne({ name })
	}

	/**
	 * 添加角色
	 * @param {CreateRoleDto} createRoleDto
	 */
	async createRole(createRoleDto: CreateRoleDto) {
		const isExitsRole = await this.getRoleByName(createRoleDto.name) // 通过名称查询角色
		if (isExitsRole) {
			throw new BusinessException('角色名称重复')
		}
		const newRole = await this.roleRepository.create(createRoleDto)
		newRole.level = 2
		newRole.dataScope = '本级'
		newRole.createBy = 'Admin'
		newRole.createTime = format(new Date())
		const saveRes = await this.roleRepository.save(newRole)
		return HttpResult.success(saveRes)
	}

	/**
	 * 删除角色
	 * @param {String} roleId
	 */
	deleteRole(roleId: string) {
		console.log(roleId)
		throw new BusinessException('删除失败')
	}

    /**
     * 修改角色
     * @param roleId
     */
	updateRole(roleId: string) {
	    return HttpResult.success('修改成功')
    }
}
